package com.zx.JDK特性.jdk1_8;

import com.zx.common.entity.User;
import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.junit.Test;

/**
 * 流是数据渠道，用于操作数据源（集合、数组等）所生成的元素序列。
 * ①Stream自己不会存储元素。
 * ②Stream不会改变源对象。相反，会返回持有新结果的新Stream。
 * ③Stream操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
 */
public class Stream2_分组 {

    List<User> list = Arrays.asList(
            new User(2L, "AAA", 20),
            new User(4L, "BBB", 40),
            new User(6L, "CCC", 40),
            new User(5L, "DDD", 50),
            new User(3L, "EEE", 30),
            new User(1L, "FFF", 10)
    );

    @Test
    public void test01() {
        //单级分组
        final Map<Integer, List<User>> collect = this.list.stream().collect(Collectors.groupingBy(User::getAge));
        System.out.println(collect);
        //{50=[User [id=5, name=DDD, age=50]], 20=[User [id=2, name=AAA, age=20]], 40=[User [id=4, name=BBB, age=40], User [id=6, name=CCC, age=40]], 10=[User [id=1, name=FFF, age=10]], 30=[User [id=3, name=EEE, age=30]]}
        System.out.println("----------------------");

        //多级分组
        final Map<Integer, Map<String, List<User>>> collect1 = this.list.stream()
                .collect(Collectors.groupingBy(User::getAge, Collectors.groupingBy(User::getName)));
        System.out.println(collect1);
        //{50={DDD=[User [id=5, name=DDD, age=50]]}, 20={AAA=[User [id=2, name=AAA, age=20]]}, 40={CCC=[User [id=6, name=CCC, age=40]], BBB=[User [id=4, name=BBB, age=40]]}, 10={FFF=[User [id=1, name=FFF, age=10]]}, 30={EEE=[User [id=3, name=EEE, age=30]]}}
        System.out.println("----------------------");

        //分区--满足条件一个区，不满足另一个区
        final Map<Boolean, List<User>> collect2 = this.list.stream()
                .collect(Collectors.partitioningBy(e -> e.getAge() > 20));
        System.out.println(collect2);
        //{false=[User [id=2, name=AAA, age=20], User [id=1, name=FFF, age=10]], true=[User [id=4, name=BBB, age=40], User [id=6, name=CCC, age=40], User [id=5, name=DDD, age=50], User [id=3, name=EEE, age=30]]}
        System.out.println("-----------------------");

        //收集各种统计数据
        final DoubleSummaryStatistics collect3 = this.list.stream().collect(Collectors.summarizingDouble(User::getAge));
        //DoubleSummaryStatistics{count=6, sum=190.000000, min=10.000000, average=31.666667, max=50.000000}-----------平均薪水31.666666666666668
        System.out.println(collect3 + "-----------平均薪水" + collect3.getAverage());

        //连接字符串
        final String collect4 = this.list.stream().map(User::getName)
                .collect(Collectors.joining(",", "-----", "-----"));
        //-----AAA,BBB,CCC,DDD,EEE,FFF-----
        System.out.println(collect4);
    }


}
